//
//  ErweimaViewController.m
//  CivilianTravel
//
//  Created by xalo on 16/7/27.
//  Copyright © 2016年 许仕杰. All rights reserved.
//

#import "ErweimaViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface ErweimaViewController ()<AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic, strong) AVCaptureSession *session;
@property(nonatomic,strong)NSString *recivestring;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *preLayer;
/**
 *      获取摄像设备
 */
@property (nonatomic, strong) AVCaptureDevice *device;
/**
 *      创建输入流
 */
@property (nonatomic, strong) AVCaptureDeviceInput *input;
/**
 *      创建输出流
 */
@property (nonatomic, strong) AVCaptureMetadataOutput *output;
@end

@implementation ErweimaViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // 开始扫描二维码
    
    // 点击返回主界面
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(dismissMainView)];
    [self.view addGestureRecognizer: tap];
    [self actionsaomiao];
    

    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void) dismissMainView {
    [self dismissViewControllerAnimated: YES completion: nil];
}
-(void)actionsaomiao{
    // 获取摄像设备
    self.device = [AVCaptureDevice defaultDeviceWithMediaType: AVMediaTypeVideo];
    // 创建输入流
    NSError *error = nil;
    self.input = [AVCaptureDeviceInput deviceInputWithDevice: self.device error: &error];
    if (error) {
        NSLog(@"请使用真机运行");
        
//            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"请使用真机调用相机" message:@"" preferredStyle:UIAlertControllerStyleAlert];
//            [self presentViewController:alert animated:YES completion:^{
//                [self performSelector:@selector(removeAlertView:) withObject:alert afterDelay:0.8];
//            }];
//        [self presentViewController:alert animated:YES completion:^{
//            [self performSelector:@selector(removeAlertView:) withObject:alert afterDelay:0.8];
//        }];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"请使用真机" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:nil, nil];
        [alert show];
        
       
        
        return;
    }
    
    // 创建输出流
    self.output = [AVCaptureMetadataOutput new];
    // 设置代理, 在主线程中刷新
    [self.output setMetadataObjectsDelegate:self queue: dispatch_get_main_queue()];
    // 初始化连接对象
    self.session = [AVCaptureSession new];
    // 设置高质量采集率
    [self.session setSessionPreset: AVCaptureSessionPresetHigh];
    // 输入输出流加入到会话中
    [self.session addInput: self.input];
    [self.session addOutput: self.output];
    // 设置扫描支持的编码格式
    self.output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    // 设置扫描layer
    self.preLayer = [AVCaptureVideoPreviewLayer layerWithSession: self.session];
    self.preLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    CGSize windowSize = [UIScreen mainScreen].bounds.size;
    self.preLayer.frame = CGRectMake((windowSize.width - 160)/4, windowSize.height/6 - 30, windowSize.width/2 + 80 , windowSize.height/2);
    [self.view.layer insertSublayer: self.preLayer atIndex:0];
    self.preLayer.cornerRadius = 10;
    self.preLayer.borderColor = [UIColor orangeColor].CGColor; ;
    self.preLayer.borderWidth = 3;
    // 启动管道, 开始捕获
    [self.session startRunning];

}
// 扫描二维码
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    // 判断是否存在数据
    // 1. 如果扫描完成，停止会话
    [self.session stopRunning];
    // 2. 删除预览图层
    [self.preLayer removeFromSuperlayer];
    if (metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *obj = [metadataObjects lastObject];
        // 二维码扫描信息处理
        NSLog(@"obj --%@", obj);
        NSLog(@"obj.corners = %@",obj.corners);
        NSLog(@"obj.stringValue = %@",obj.stringValue);
        
        NSString *string = [NSString stringWithFormat:@"%@",obj.stringValue];
        self.recivestring =string;
        //        NSURL *URL = [NSURL URLWithString:string];
        
        
        UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(0, 50, self.view.frame.size.width, self.view.frame.size.height-50)];
        lable.backgroundColor = [UIColor whiteColor];
        lable.text=self.recivestring;
        lable.textAlignment = NSTextAlignmentCenter;
        [self.view addSubview:lable];
        
        [self validateUrl:[self smartURLForString:string]];
        
        
        NSLog(@"扫码结果：%@",string);
    }else{
        
    }
}
- (NSURL *)smartURLForString:(NSString *)str
{
    NSURL *     result;
    NSString *  trimmedStr;
    NSRange     schemeMarkerRange;
    NSString *  scheme;
    
    assert(str != nil);
    
    result = nil;
    
    trimmedStr = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ( (trimmedStr != nil) && (trimmedStr.length != 0) ) {
        schemeMarkerRange = [trimmedStr rangeOfString:@"://"];
        
        if (schemeMarkerRange.location == NSNotFound) {
            result = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", trimmedStr]];
        } else {
            scheme = [trimmedStr substringWithRange:NSMakeRange(0, schemeMarkerRange.location)];
            assert(scheme != nil);
            
            if ( ([scheme compare:@"http"  options:NSCaseInsensitiveSearch] == NSOrderedSame)
                || ([scheme compare:@"https" options:NSCaseInsensitiveSearch] == NSOrderedSame) ) {
                result = [NSURL URLWithString:trimmedStr];
            } else {
                // It looks like this is some unsupported URL scheme.
            }
        }
    }
    
    return result;
}
//判断
-(void) validateUrl: (NSURL *) candidate {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:candidate];
    [request setHTTPMethod:@"HEAD"];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"error %@",error);
        if (error) {
            NSLog(@"不可用");
            
            
            
            
        }else{
            NSLog(@"可用");
            [[UIApplication sharedApplication]openURL:candidate];
            
        }
    }];
    [task resume];
}
- (void)removeAlertView:(UIAlertController*)alert
{
    //alertView消失
    [alert dismissViewControllerAnimated:YES completion:nil];
     
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
